<?php
/**
* @file $Id: AddAbsences.php 437 2007-04-23 00:57:51Z focus-sis $
* @package Focus/SIS
* @copyright Copyright (C) 2006 Andrew Schmadeke. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
* Focus/SIS is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/

if (!$_REQUEST['month']) {
	$_REQUEST['month'] = date('m');
}
else {
	$_REQUEST['month'] = MonthNWSwitch($_REQUEST['month'], 'tonum');
}	

if (!$_REQUEST['year']) {
	$_REQUEST['year'] = date('Y');
}
else {
	$_REQUEST['year'] = $_REQUEST['year'] < 1900
			? '20'.$_REQUEST['year']
			: $_REQUEST['year'];
}

if ($_REQUEST['modfunc'] == 'save') {
	if(count($_REQUEST['period']) 
	&& count($_REQUEST['student']) 
	&& count($_REQUEST['dates'])
	) {
		foreach ($_REQUEST['period'] as $period_id=>$yes) {
			$periods_list .= ",'".$period_id."'";
		}		
		
		$periods_list = substr($periods_list, 1);

		foreach ($_REQUEST['student'] as $student_id=>$yes) {
			$students_list .= ",'".$student_id."'";
		}
		
		$students_list = substr($students_list, 1);

		$current_RET = DBGet(DBQuery("
				SELECT       STUDENT_ID
				 ,           PERIOD_ID
				 ,           SCHOOL_DATE 
				FROM         ATTENDANCE_PERIOD 
				WHERE        EXTRACT(MONTH FROM SCHOOL_DATE)='".($_REQUEST['month'] * 1)."' 
				 AND         EXTRACT(YEAR FROM SCHOOL_DATE) = '$_REQUEST[year]' 
				 AND         PERIOD_ID IN ($periods_list) 
				 AND         STUDENT_ID IN ($students_list)
				 "), array(), array('STUDENT_ID','SCHOOL_DATE','PERIOD_ID'));
				 
		foreach ($_REQUEST['student'] as $student_id=>$yes) {
			foreach ($_REQUEST['dates'] as $date=>$yes) {
				$time = mktime(0, 0, 0, (substr($date, 5, 2) * 1)
						,(substr($date, 8, 2) * 1), substr($date, 2, 2));
						
				$day = DayNameToLetter(date('D', $time));
								
				$mp_list = GetAllMP('QTR',GetCurrentMP('QTR',$date));
				$course_periods_RET = DBGet(DBQuery("
						SELECT       s.COURSE_PERIOD_ID
						 ,           cp.PERIOD_ID
						FROM         SCHEDULE s
						 ,           COURSE_PERIODS cp
						 ,           ATTENDANCE_CALENDAR ac
						 ,           SCHOOL_PERIODS sp 
						WHERE        sp.PERIOD_ID = cp.PERIOD_ID
						 AND         ac.SCHOOL_DATE = '$date'
						 AND         ac.CALENDAR_ID = cp.CALENDAR_ID
						 AND (       ac.BLOCK = sp.BLOCK
						  OR         sp.BLOCK IS NULL ) 
						 AND         s.COURSE_PERIOD_ID = cp.COURSE_PERIOD_ID
						 AND         s.STUDENT_ID = '$student_id'
						 AND         cp.PERIOD_ID IN ($periods_list)
						 AND         cp.DOES_ATTENDANCE = 'Y'
						 AND (       '$date' BETWEEN s.START_DATE AND s.END_DATE
						  OR    (    s.END_DATE IS NULL
						   AND       '$date'>=s.START_DATE ) )
						 AND         cp.DAYS LIKE '%".$day."%'
						 AND         cp.MARKING_PERIOD_ID IN ($mp_list)
						 AND         s.MARKING_PERIOD_ID IN ($mp_list)
						"), array(), array('PERIOD_ID'));
				
				foreach ($_REQUEST['period'] as $period_id=>$yes) {
					if (!$current_RET[$student_id][$date][$period_id]) {
					
						$course_period_id = 
								$course_periods_RET[$period_id][1]['COURSE_PERIOD_ID'];
					
						if ($course_period_id) {
							DBQuery("
									INSERT INTO  ATTENDANCE_PERIOD 
									(  STUDENT_ID
									 , SCHOOL_DATE
									 , PERIOD_ID
									 , MARKING_PERIOD_ID
									 , COURSE_PERIOD_ID
									 , ATTENDANCE_CODE
									 , ATTENDANCE_REASON
									 , ADMIN
									) VALUES
									(  '$student_id'
									 , '$date'
									 , '$period_id'
									 , '".GetCurrentMP('QTR',$date)."'
									 , '$course_period_id'
									 , '$_REQUEST[absence_code]'
									 , '$_REQUEST[absence_reason]'
									 , 'Y'
									)");
						}
					}
					else
					{
						DBQuery("
								UPDATE       ATTENDANCE_PERIOD 
								SET          ATTENDANCE_CODE = '$_REQUEST[absence_code]'
								 ,           ATTENDANCE_REASON = '$_REQUEST[absence_reason]'
								 ,           ADMIN = 'Y' 
								WHERE        STUDENT_ID = '$student_id' 
								 AND         SCHOOL_DATE = '$date' 
								 AND         PERIOD_ID = '$period_id'
								");
					}
				}
				UpdateAttendanceDaily($student_id
						, $date
						, $_REQUEST['absence_reason']
							? $_REQUEST['absence_reason']
							: false
						);
			}
		}
		unset($_REQUEST['modfunc']);
		$note = _('Absence records were added for the selected students.');
	}
	else
		BackPrompt(_('You must choose at least one period, one date, and one student.'));
}

DrawHeader(ProgramTitle());

if (!$_REQUEST['modfunc']) {
	$extra['link'] = array('FULL_NAME'=>false);
	$extra['SELECT'] = '
			,           CAST (NULL AS CHAR(1)) AS CHECKBOX';

	if ($note) {
		DrawHeader('<IMG SRC="assets/check.gif" />'.$note);
	}
	
	if ($_REQUEST['search_modfunc'] == 'list') {
		echo "
		<FORM action=Modules.php?modname=$_REQUEST[modname]&modfunc=save METHOD=POST>";
		
		DrawHeader('',SubmitButton(_("Add Absences to Selected Students")));

		echo '
			<BR>
			<CENTER>
				<TABLE bgcolor="#'.Preferences('COLOR').'">
					<TR>
						<TD align="'.ALIGN_RIGHT.'">
							'._("Add Absence to Periods").'
						</TD>
						<TD>
							<TABLE>
								<TR>';
									
		$periods_RET = DBGet(DBQuery("
				SELECT       SHORT_NAME
				 ,           PERIOD_ID 
				FROM         SCHOOL_PERIODS 
				WHERE        SYEAR = '".UserSyear()."' 
				 AND         SCHOOL_ID = '".UserSchool()."' 
				ORDER BY     SORT_ORDER
				"));
				
		foreach ($periods_RET as $period) {
			echo '
									<TD>
										<INPUT type="CHECKBOX" 
												value="Y" 
												name="period['.$period['PERIOD_ID'].']"
										/>
										'.$period['SHORT_NAME'].'
									</TD>
								';
		}
		echo 					'</TR>
							</TABLE>
						</TD>
					</tr>
					<TR>
						<TD align="'.ALIGN_RIGHT.'">
							'._('Absence Code').'
						</TD>
						<TD>
							<SELECT name="absence_code">
							';
								
		$codes_RET = DBGet(DBQuery("
				SELECT       TITLE
				 ,           ID 
				FROM         ATTENDANCE_CODES 
				WHERE        SYEAR = '".UserSyear()."' 
				 AND         SCHOOL_ID = '".UserSchool()."' 
				 AND         TABLE_NAME = '0' 
				ORDER BY     SORT_ORDER
				"));
				
		foreach ($codes_RET as $code) {
			echo            '	<OPTION value="'.$code['ID'].'">
									'.$code['TITLE'].'
								</OPTION>
							';
		}
		
		echo                '</SELECT>
						</TD>
					</TR>
					<TR>
						<TD align="'.ALIGN_RIGHT.'">
							'._('Absence Reason').'
						</TD>						
						<TD>
							<INPUT type="text" name="absence_reason">
						</TD>
					</TR>
					'
		//echo '<TR><TD colspan=2>Date<BR> &nbsp; &nbsp; <small>Between</small> '.PrepareDate(DBDate(),'_begin',true,array('hidden'=>true)).' <small>&</small> '.PrepareDate(DBDate(),'_end',true,array('hidden'=>true)).'</TD></TR>';
					.'<TR>
						<TD colspan="2" align="center">';
						
		$time = mktime(0, 0, 0, $_REQUEST['month'] * 1
				, 1, substr($_REQUEST['year'], 2));
				
		echo PrepareDate(strtoupper(date("d-M-y", $time))
				, ''
				, false
				, array('M'=>1, 'Y'=>1, 'submit'=>true)
				);

		$skip = date("w", $time);
		$last = 31;
		while(!checkdate($_REQUEST['month']*1, $last, substr($_REQUEST['year'],2))) {
			$last--;
		}
		
		echo '
							<TABLE>
								<TR>
									<TH>S</TH>
									<TH>M</TH>
									<TH>T</TH>
									<TH>W</TH>
									<TH>Th</TH>
									<TH>F</TH>
									<TH>S</TH>
								</TR>
								<TR>
									';
									
		$calendar_RET = DBGet(DBQuery("
				SELECT       SCHOOL_DATE 
				FROM         ATTENDANCE_CALENDAR 
				WHERE        SYEAR = '".UserSyear()."' 
				 AND         SCHOOL_ID = '".UserSchool()."' 
				 AND         MINUTES != '0' 
				 AND         EXTRACT(MONTH FROM SCHOOL_DATE) = '".($_REQUEST['month'] * 1)."'
				"), array(), array('SCHOOL_DATE'));
				 
		for ($i=1; $i<=$skip; $i++) {
			echo '
									<TD>&nbsp;</TD>';
		}

		for ($i=1; $i<=$last; $i++)	{
			$this_date = $_REQUEST['year'].'-'.$_REQUEST['month'].'-'.($i<10?'0'.$i:$i);
			if (!$calendar_RET[$this_date]) {
				$disabled = ' DISABLED';
			}
			elseif(date('Y-m-d') == $this_date) {
				$disabled = ' CHECKED';
			}
			else {
				$disabled = '';
			}

			echo '
									<TD align="'.ALIGN_RIGHT.'">
										'.$i.'
										<INPUT type="checkbox" name="dates['.$this_date.']" value="Y"'.$disabled.' />
									</TD>';
			$skip++;
			
			if(($skip % 7 == 0) 
			&& ($i != $last)
			) {
				echo '
								</TR>
								<TR>';
			}
		}
		echo '
								</TR>
							</TABLE>
						</TD>
					</TR>
				</TABLE>
			</CENTER>';
	}

/*	Widgets('activity');
	Widgets('course');
	Widgets('absences');
*/
	Widgets('all');
	$extra['functions'] = array('CHECKBOX'=>'_makeChooseCheckbox');
	$extra['columns_before'] = array('CHECKBOX'=>'
			</A>
				<INPUT type="checkbox" 
						value="Y" 
						name="controller" 
						onclick="checkAll(this.form,this.form.controller.checked,\'student\');" 
				/>
			<A>');

	$extra['new'] = true;

	Search('student_id',$extra);
	if ($_REQUEST['search_modfunc'] == 'list') {
		echo '
			<BR />
			<CENTER>
				'.SubmitButton(gettext("Add Absences to Selected Students")).'
			</CENTER>
		</FORM>';
	}
}

function _makeChooseCheckbox($value,$title) {
	global $THIS_RET;

	if ($_REQUEST['stuid']) {
		$checked = ' CHECKED';
	}
	
	return '
			<INPUT type="checkbox" 
					name="student['.$THIS_RET['STUDENT_ID'].']" 
					value="Y"'
					.$checked.' 
			/>';
}
?>